package generatorGraphics.graphics;

import grammaticalClasses.nwConsole.ShowMote;
import grammaticalClasses.nwConsole.ShowStatDay;
import grammaticalClasses.nwConsole.ShowStatShort;
import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.SeriesException;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;

public class MoteLatency2 extends Graph {
    
    private ArrayList<String> parameterFilterTimeInterval = new ArrayList<>();
    private ArrayList<String> parameterFilterGeneric = new ArrayList<>();
    private ArrayList<String> parameterFilterDays = new ArrayList<>();
    
    public MoteLatency2(){
        name = "Mote Latency";
        help = "Help of Mote Latency";
        
        isFilter = true;
        
        configUnitOptions();
        
        commands.add("ShowStatCur");
        commands.add("ShowStatShort");
        commands.add("ShowMote");
        commands.add("ShowStatDay");
    }
    
    private void configUnitOptions(){

        // Adicionando as unidades
        unitList.add("Time Interval(15min)");
        unitList.add("Generic");
        unitList.add("Days");
        
        //Adicionando as opções
        //--Não existe definição de Opções
    }
        
    @Override
    protected void createGraph(String unit) {
        
        int indice;
        
//        if(search == null){
//            search = new SearchCommands(commands);
//            answer = (ArrayList<Object>) search.getCommandsAnswer();
//        }
        
        switch (unit){
            case "Time Interval(15min)":
                
                indice = search.getAnswer(commands, "ShowStatShort");
                
                chartPanel = new ChartPanel(buildGraphTimeIntervalFilter(null, (ArrayList<ShowStatShort>) answer.get(indice)));
                chartPanel.setBackground(Color.LIGHT_GRAY);
                chartPanel.setPreferredSize(new Dimension(700, 350)); 
                chartPanel.setDomainZoomable(false);
                chartPanel.setRangeZoomable(false);

                break;
            case "Generic":
                
                indice = search.getAnswer(commands, "ShowMote");
                
                chartPanel = new ChartPanel(buildGraphGenericFilter(null, (ArrayList<ShowMote>) answer.get(indice)));
                chartPanel.setBackground(Color.LIGHT_GRAY);
                chartPanel.setPreferredSize(new Dimension(700, 350)); 
                chartPanel.setDomainZoomable(false);
                chartPanel.setRangeZoomable(false);

                break;
            case "Days":

                indice = search.getAnswer(commands, "ShowStatDay");
                
                chartPanel = new ChartPanel(buildGraphDaysFilter(null, (ArrayList<ShowStatDay>) answer.get(indice)));
                chartPanel.setBackground(Color.LIGHT_GRAY);
                chartPanel.setPreferredSize(new Dimension(700, 350));
                chartPanel.setDomainZoomable(false);
                chartPanel.setRangeZoomable(false);

                break;
            default:
                chartPanel = new ChartPanel(null);
                
                break;
        }
    }    
    
    @Override
    public Object getFilter(String unit){
        
        switch (unit){
            case "Time Interval(15min)":
                
                parameterFilter = parameterFilterTimeInterval;
                break;
            case "Generic":

                parameterFilter = parameterFilterGeneric;
                break;
            case "Days":
                
                parameterFilter = parameterFilterDays;
                break;
            default:
                
                break;
        }
        return parameterFilter;
    }
    
    @Override
    public ChartPanel filtrate(String unit, Object parameterFiltrate){
      
        ChartPanel chartAux = new ChartPanel(null);
        int indice;
        
        switch (unit){
            case "Time Interval(15min)":
                
                indice = search.getAnswer(commands, "ShowStatShort");
                
                chartAux = new ChartPanel(buildGraphTimeIntervalFilter(parameterFiltrate, (ArrayList<ShowStatShort>) answer.get(indice)));
                chartAux.setBackground(Color.LIGHT_GRAY);
                chartAux.setPreferredSize(new Dimension(700, 350)); 
                chartAux.setDomainZoomable(false);
                chartAux.setRangeZoomable(false);
                
                break;
            case "Generic":
                
                indice = search.getAnswer(commands, "ShowMote");
                
                chartAux = new ChartPanel(buildGraphGenericFilter(parameterFiltrate, (ArrayList<ShowMote>) answer.get(indice)));
                chartAux.setBackground(Color.LIGHT_GRAY);
                chartAux.setPreferredSize(new Dimension(700, 350)); 
                chartAux.setDomainZoomable(false);
                chartAux.setRangeZoomable(false);

                break;
            case "Days":

                indice = search.getAnswer(commands, "ShowStatDay");
                
                chartAux = new ChartPanel(buildGraphDaysFilter(parameterFiltrate, (ArrayList<ShowStatDay>) answer.get(indice)));
                chartAux.setBackground(Color.LIGHT_GRAY);
                chartAux.setPreferredSize(new Dimension(700, 350));
                chartAux.setDomainZoomable(false);
                chartAux.setRangeZoomable(false);

                break;
            default:
                chartAux = new ChartPanel(null);
                break;
        }
        
        return chartAux;
    }

    private JFreeChart buildGraphTimeIntervalFilter(Object paramaterFiltrate, ArrayList<ShowStatShort> auxShort){
    
        ArrayList<TimeSeries> timeSeriesList = new ArrayList<>();
        parameterFilterTimeInterval = new ArrayList<>();
        
        if(paramaterFiltrate == null){
            if(auxShort.size() > 0){
            for(int j=0; j<auxShort.get(0).getMoteStats().size(); j++){
                TimeSeries timeSeries = new TimeSeries(auxShort.get(0).getMoteStats().get(j).getId());
                parameterFilterTimeInterval.add(auxShort.get(0).getMoteStats().get(j).getId().toString());
                timeSeriesList.add(timeSeries);
            }
            }
        } else{
            if(auxShort.size() > 0){
            for(int j=0; j<auxShort.get(0).getMoteStats().size(); j++){
                boolean auxBool = false;
                for(int k=0; k< ((ArrayList<String>)paramaterFiltrate).size(); k++){
                    if(((ArrayList<String>)paramaterFiltrate).get(k).equals(
                            auxShort.get(0).getMoteStats().get(j).getId().toString())){
                        auxBool = true;
                    }
                }
                if(auxBool){
                    TimeSeries timeSeries = new TimeSeries(auxShort.get(0).getMoteStats().get(j).getId());
                    timeSeriesList.add(timeSeries);
                }
            }
            }
        }
        
        return buildGraphTimeInterval(timeSeriesList, auxShort);
        
    }
    
    private JFreeChart buildGraphGenericFilter(Object parameterFiltrate, ArrayList<ShowMote> auxMote) {
        DefaultCategoryDataset dataset2 = new DefaultCategoryDataset();
        parameterFilterGeneric = new ArrayList<>();
        
        if(parameterFiltrate == null){
            for(int i=0; i< auxMote.size(); i++){
                parameterFilterGeneric.add(auxMote.get(i).getIdMote().toString());
                dataset2.addValue(auxMote.get(i).getLate(),
                    "Devices", 
                    auxMote.get(i).getIdMote());
            }
        } else{
            for(int i=0; i< auxMote.size(); i++){
                boolean auxBool = false;
                for(int k=0; k< ((ArrayList<String>)parameterFiltrate).size(); k++){
                    if(((ArrayList<String>)parameterFiltrate).get(k).equals(
                            auxMote.get(i).getIdMote().toString())){
                        auxBool = true;
                    }
                }
                if(auxBool){
                    dataset2.addValue(auxMote.get(i).getLate(),
                        "Devices", 
                        auxMote.get(i).getIdMote());
                }
            }
        }

        return buildGraphGeneric(dataset2);
    }

    private JFreeChart buildGraphDaysFilter(Object parameterFiltrate, ArrayList<ShowStatDay> auxDay) {

        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        parameterFilterDays = new ArrayList<>();
        if(parameterFiltrate == null){
            for(int k=0; k<auxDay.size(); k++){
                parameterFilterDays = new ArrayList<>();
                for(int j=0; j<auxDay.get(k).getMoteStats().size(); j++){
                    parameterFilterDays.add(auxDay.get(k).getMoteStats().get(j).getId().toString());
                    dataset.addValue(auxDay.get(k).getMoteStats().get(j).getLate(),
                        "Day " + auxDay.get(k).getidDay(),
                        auxDay.get(k).getMoteStats().get(j).getId());
                }
            }
        } else{
            for(int k=0; k<auxDay.size(); k++){
                for(int j=0; j<auxDay.get(k).getMoteStats().size(); j++){
                    boolean auxBool = false;
                    for(int i=0; i< ((ArrayList<String>)parameterFiltrate).size(); i++){
                        if(((ArrayList<String>)parameterFiltrate).get(i).equals(
                                auxDay.get(k).getMoteStats().get(j).getId().toString())){
                            auxBool = true;
                        }
                    }
                    if(auxBool){
                        dataset.addValue(auxDay.get(k).getMoteStats().get(j).getLate(),
                            "Day " + auxDay.get(k).getidDay(),
                            auxDay.get(k).getMoteStats().get(j).getId());
                    }
                }
            }
        }

        return buildGraphDays(dataset);
        
    }
    
    private JFreeChart buildGraphTimeInterval(ArrayList<TimeSeries> timeSeriesList,
            ArrayList<ShowStatShort> auxShort){
    
        TimeSeriesCollection timeseriescollection = new TimeSeriesCollection();
        for(int i=0; i<timeSeriesList.size(); i++){
            timeseriescollection.addSeries(timeSeriesList.get(i));
        }
        
        for(int i=0; i<timeSeriesList.size(); i++){
            for(int k=0; k<auxShort.size(); k++){
                for(int j=0; j<auxShort.get(k).getMoteStats().size(); j++){
                    if(timeSeriesList.get(i).getKey().equals(auxShort.get(k).getMoteStats().get(j).getId())){
                        String[] aux1 = (auxShort.get(k).getHourFinal()).split(":");
                        String[] aux2 = (auxShort.get(k).getDataFinal()).split("/");
                        aux2[2] = "20" + aux2[2];

                        try{
                            if((isNumber(aux1[2])) &&
                                (isNumber(aux1[1])) &&
                                (isNumber(aux1[0])) &&
                                (isNumber(aux2[2])) &&
                                (isNumber(aux2[1])) &&
                                (isNumber(aux2[0]))){

                                timeSeriesList.get(i).add(new Second(
                                    Integer.valueOf(aux1[2]), 
                                    Integer.valueOf(aux1[1]), 
                                    Integer.valueOf(aux1[0]), 
                                    Integer.valueOf(aux2[1]), 
                                    Integer.valueOf(aux2[0]), 
                                    Integer.valueOf(aux2[2])), 
                                    auxShort.get(k).getMoteStats().get(j).getLate());
                            }
                        } catch(SeriesException ex){
                            System.out.println("[Erro-MoteLatency] " + ex.toString());
                        }
                    }
                }
            }
        }

        JFreeChart chart = ChartFactory.createTimeSeriesChart(name, "Time Interval(15min)", 
                "Seconds", timeseriescollection, true, true, false);
        chart.setBackgroundPaint(new Color(238, 238, 238));

        XYPlot xyplot = (XYPlot) chart.getPlot();
        //xyplot.setInsets(new RectangleInsets(0.0D, 0.0D, 0.0D, 20D));
        //ValueMarker valuemarker = new ValueMarker(700D);
        //valuemarker.setPaint(Color.blue);
        //valuemarker.setAlpha(0.8F);
        //xyplot.addRangeMarker(valuemarker);
        xyplot.setBackgroundPaint(null);
        //xyplot.setBackgroundImage(JFreeChart.INFO.getLogo());
        //xyplot.getDomainAxis().setLowerMargin(0.0D);
        xyplot.getDomainAxis().setVerticalTickLabels(true);
        
        return chart;
        
    }
    
    private JFreeChart buildGraphGeneric(DefaultCategoryDataset dataset2){
    
        JFreeChart chart2 = ChartFactory.createBarChart(name, 
                "", "Seconds", 
                dataset2, PlotOrientation.VERTICAL, 
                true, true, false);
        chart2.setBackgroundPaint(new Color(238, 238, 238));

        CategoryPlot plot2 = (CategoryPlot) chart2.getPlot();
        plot2.setBackgroundPaint(Color.white);
        plot2.setDomainGridlinePaint(Color.white);
        plot2.setDomainGridlinesVisible(true);
        plot2.setRangeGridlinePaint(Color.white);

        return chart2;
        
    }
    
    private JFreeChart buildGraphDays(DefaultCategoryDataset dataset){
    
        JFreeChart chart3 = ChartFactory.createBarChart(name, 
                "Devices",
                "Seconds",
                dataset,
                PlotOrientation.VERTICAL,
                true,
                true,
                false);
        chart3.setBackgroundPaint(new Color(238, 238, 238));

        CategoryPlot plot = (CategoryPlot) chart3.getPlot();
        plot.setBackgroundPaint(Color.white);
        plot.setDomainGridlinePaint(Color.white);
        plot.setDomainGridlinesVisible(true);
        plot.setRangeGridlinePaint(Color.white);
        
        return chart3;
        
    }
    
}
